package org.gitman.agent.gui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import org.gitman.agent.platform.AddedAgentInfo;
import org.gitman.agent.platform.GraphEditor;
import org.gitman.agent.platform.PlatformManager;

import com.mxgraph.model.mxCell;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.util.mxConstants;
import com.mxgraph.util.mxUtils;
import com.mxgraph.view.mxGraph;

public class GraphMouseAdapter extends MouseAdapter{
	
	private GraphDisplPanel graphDisplPanel;
	private GraphEditor graphEditor;
	private PlatformManager platformManager;
	
	public GraphMouseAdapter(GraphDisplPanel graphDisplPanel, PlatformManager platformManager){
		this.graphDisplPanel = graphDisplPanel;
		this.platformManager = platformManager;		
		graphEditor = platformManager.getGraphEditor();
	}

	@Override
	public void mouseClicked(MouseEvent arg0) {
		mxGraph graph = graphEditor.getGraph();
		mxGraphComponent graphComponent = graphEditor.getGraphComponent();
		if(graphEditor.isEdited()){
			if(arg0.getClickCount() == 2 && arg0.getButton() == MouseEvent.BUTTON1 ){
				graphDisplPanel.insertVertex(arg0.getX()-GraphDisplPanel.SIZE/2, arg0.getY()-GraphDisplPanel.SIZE/2);
			}else if (arg0.getButton() == MouseEvent.BUTTON3){
				graph.getModel().beginUpdate();
				try{
					graph.removeCells(graph.getSelectionCells());
				}finally{
					graph.getModel().endUpdate();
				}
			}
		}else{
			AddedAgentInfo info = platformManager.getSimulation().getAgentManager().getAddedAgentInfo();
			if(info != null && info.canSelectPoints()){
				mxCell point = (mxCell) graph.getSelectionCell();
				if(point != null && point.isVertex()){					
					graphComponent.refresh();
					if(arg0.getClickCount() == 2 && arg0.getButton() == MouseEvent.BUTTON1 ){	
						info.setStartPoint(point);
					}else if (arg0.getButton() == MouseEvent.BUTTON3){	
						info.setEndPoint(point);
					}
				}
			}
		}
	}
}
